package com.zlzlib.okhttp.utils;

import com.zlzlib.okhttp.xml.SoapEnvelope;
import com.zlzlib.okhttp.xml.XmlResultUtil;
import okhttp3.Headers;
import okhttp3.RequestBody;
import org.springframework.util.ObjectUtils;

/**
 * @DateTime: 2024/4/16 15:09
 * @Author zlz
 * @Version 1.0
 */
public abstract class BaseReqUtil {

    private final HttpRequestUtil httpRequestUtil;

    protected BaseReqUtil(HttpRequestUtil httpRequestUtil) {
        this.httpRequestUtil = httpRequestUtil;
    }

    /**
     * 日志
     *
     * @param s 内容
     */
    protected abstract void log(String s);

    /**
     * 头部数据打印
     *
     * @param head 头部
     * @return 打印的数据
     */
    protected abstract String headToString(Headers.Builder head);

    protected String postSoapAction(String url, String soapAction, SoapEnvelope soapEnvelope) {
        long time = System.currentTimeMillis();
        String response = httpRequestUtil.postSoap(url, soapAction, soapEnvelope);
        String msg = "地址:[" + url + "] 参数:[" + soapEnvelope.toString() +
                "] 结果:[" + response + "] 耗时:" + (System.currentTimeMillis() - time);
        log(msg);
        if (ObjectUtils.isEmpty(response)) {
            return "";
        }
        return XmlResultUtil.xmlGetLastString(response);
    }

    protected String postRequest(String url, String json, Headers.Builder head) {
        long time = System.currentTimeMillis();
        if (head == null) {
            head = new Headers.Builder();
        }
        String response = httpRequestUtil.postRequest(url,
                RequestBody.create(json, OkHttpUtil.mediaJson()), head);
        String msg = "地址:[" + url + "] 参数:[" + json + "] 头部:[" + headToString(head) +
                "] 结果:[" + response + "] 耗时:" + (System.currentTimeMillis() - time);
        log(msg);
        if (ObjectUtils.isEmpty(response)) {
            return "";
        }
        return response;
    }
}
